package com.example.demotest.service;

import com.example.demotest.exception.UsernameAlreadyExistsException;
import com.example.demotest.pojo.Order;
import com.example.demotest.pojo.Order.DeliveryStatus;
import com.example.demotest.pojo.ResponseMessage;
import com.example.demotest.pojo.OrderStatus;
import com.example.demotest.pojo.Rider;
import com.example.demotest.pojo.dto.RiderDto;
import com.example.demotest.repository.*;
import com.example.demotest.util.JWT;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class RiderService implements IRiderService {

    @Autowired
    private OrderRepository orderRepository;
    private RiderRepository riderRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JWT jwtUtil;

    public RiderService(OrderRepository orderRepository, RiderRepository riderRepository) {
        this.orderRepository = orderRepository;
        this.riderRepository = riderRepository;
    }
    /**
     * 骑手登录
     */
    @Override
    public ResponseMessage<Rider> login(RiderDto riderDto) {
        Optional<Rider> riderOptional = findByRiderName(riderDto.getRiderName());

        if (riderOptional.isPresent()) {
            Rider rider = riderOptional.get();
            if (passwordEncoder.matches(riderDto.getPassword(), rider.getPassword())) {
                System.out.println("骑手登录成功");
                String token = JWT.generateRiderToken(rider.getRiderId());
                return ResponseMessage.successWithToken(rider, token);
            }
        }

        return ResponseMessage.error(401, "骑手账号或密码错误");
    }

    /**
     * 骑手注册
     */
    @Override
    public Rider register(RiderDto riderDto) {
        // 骑手名是否存在
        if (riderRepository.findByRiderName(riderDto.getRiderName()).isPresent()) {
            throw new UsernameAlreadyExistsException("骑手用户名已存在");
        }

        Rider rider = new Rider();
        rider.setRiderName(riderDto.getRiderName());
        rider.setPassword(passwordEncoder.encode(riderDto.getPassword()));
        rider.setNickname(riderDto.getNickname());
        rider.setPhone(riderDto.getPhone());

        // 保存
        return riderRepository.save(rider);
    }

    private Optional<Rider> findByRiderName(String riderName) {
        return riderRepository.findByRiderName(riderName);
    }
    @Override
    public List<Order> getAvailableOrders() {
        return orderRepository.findByOrderStatusAndDeliveryStatus(
                OrderStatus.WAIT_SHIP.getCode(),
                DeliveryStatus.WAITING_FOR_PICKUP
        );
    }

    @Override
    public List<Order> getMyOrders(Integer riderId) {
        return orderRepository.findByRiderId(riderId);
    }

    @Override
    public ResponseMessage<String> acceptOrder(Integer riderId, Integer orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order == null) {
            return ResponseMessage.error(404, "订单不存在");
        }
        if (order.getOrderStatus() != OrderStatus.WAIT_SHIP.getCode()
                || order.getDeliveryStatus() != DeliveryStatus.WAITING_FOR_PICKUP) {
            return ResponseMessage.error(400, "订单当前不可接单");
        }

        order.setRiderId(riderId);
        order.setDeliveryStatus(DeliveryStatus.IN_TRANSIT);
        order.setPickupTime(LocalDateTime.now());
        orderRepository.save(order);
        return ResponseMessage.success("接单成功");
    }

    @Override
    public ResponseMessage<String> completeOrder(Integer riderId, Integer orderId) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order == null) {
            return ResponseMessage.error(404, "订单不存在");
        }
        if (!riderId.equals(order.getRiderId())) {
            return ResponseMessage.error(403, "无权操作此订单");
        }
        if (order.getDeliveryStatus() != DeliveryStatus.IN_TRANSIT) {
            return ResponseMessage.error(400, "订单状态不允许完成");
        }

        order.setDeliveryStatus(DeliveryStatus.DELIVERED);
        order.setOrderStatus(OrderStatus.COMPLETED.getCode());
        order.setDeliveryTime(LocalDateTime.now());
        orderRepository.save(order);
        return ResponseMessage.success("订单完成");
    }
}
